<?php

namespace app\admin\model;

use app\common\model\UploadFile as UploadFileModel;
use think\facade\Request;

/**
 * 文件库模型
 * Class UploadFile
 * @package app\store\model
 */
class UploadFile extends UploadFileModel
{

    
    /**
     * 获取列表记录
     * @param int $groupId 分组id
     * @param string $fileType 文件类型
     * @param bool|int $isRecycle
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($groupId = 0, $fileType = '')
    {
        $where = ['is_user' => 0, 'is_delete' => 0 , 'is_recycle' => 0];
        // 文件分组
        $groupId == -1 && $where['is_recycle'] = 1;

        $groupId > -1 && $where['group_id'] = (int)$groupId;
        // 文件类型
        !empty($fileType) && $where['file_type'] = trim($fileType);
        // 查询列表数据
        return $this->with(['upload_group'])
            ->where($where)
            ->order(['file_id' => 'desc'])
            ->paginate(32, false, [
                'query' => Request::instance()->request()
            ]);
    }

    /**
     * 移入|移出回收站
     * @param bool $isRecycle
     * @return false|int
     */
    public function setRecycle($fileIds = [],$isRecycle = true)
    {
        return $this->where('file_id', 'in', $fileIds)->save(['is_recycle' => (int)$isRecycle]);
    }

    /**
     * 批量软删除
     * @param $fileIds
     * @return $this
     */
    public function softDelete($fileIds)
    {
        if(!$data = $this->where('file_id', 'in', $fileIds)->field('file_name')->select())
        {
            $this->error = "文件已被删除!";
            return false;
        }

        // 查询用户头像是否占用
        if(AdminUser::where('image_id', 'in', $fileIds)->value('admin_user_id'))
        {
            $this->error = "该图片有用户正在作为头像,无法删除!";
            return false;
        }

        // 查询商品是否正在使用

        try {
            $this->startTrans();
            $this->where('file_id', 'in', $fileIds)->delete();
            $root_path = app()->getRootPath();
            foreach($data as  $value)
            {
                //判断是否本地图片是则删除本地文件
                if(env('filesystem.driver','local') == 'local')
                {
                    unlink($root_path . 'public' . DS . 'uploads'. DS . str_replace('\\','/',$value['file_name']));
                }
            }
            $this->commit();
            return true;
        } catch (\Throwable $th) {
            //throw $th;
            $this->error = $th->getMessage();
            $this->rollback();
            return false;
        }

    }

    /**
     * 批量移动文件分组
     * @param $group_id
     * @param $fileIds
     * @return $this
     */
    public function moveGroup($group_id, $fileIds)
    {
        
        return $this->where('file_id', 'in', implode(',',$fileIds))->update(['group_id'=>$group_id]);
    }

}
